<?php

namespace app\process;

use Swoole\Coroutine;
use zhanshop\App;
use zhanshop\client\Httpclient;
use zhanshop\Log;
use zhanshop\util\Tailf;

class Logstash
{
    protected $fileLogs = [];

    protected $cloudUrl = '';
    public function __construct()
    {
        $this->cloudUrl = 'http://'.App::config()->get('bridge.ip').':'.(intval(App::config()->get('bridge.port')) - 1).'/v1/cloud.log/'.App::config()->get('bridge.token');
    }
    public function execute($server)
    {
        $msg = "采集进程启动, 进程".getmypid();
        Log::errorLog(SWOOLE_LOG_DEBUG, $msg);
        $obj = new Tailf();
        $logstash = App::config()->get('logstash');
        foreach($logstash['input'] ?? [] as $log){
            $path = $log['path'] ?? '';
            if($path && file_exists($path)){
                $format = $log['format'];
                $obj->addWatch($path, function ($path, $data)use ($format){
                    Coroutine::create(function () use ($path, $data, $format){
                        try {
                            $this->$format($path, $data);
                        }catch (\Throwable $throwable){}
                    });
                }, function ($path){
                    unset($this->fileLogs[$path]);
                });
            }
        }
        $obj->start();
    }

    /**
     * nginx日志
     * @param $path
     * @param $data
     * @return void
     */
    public function nginx($path, $data)
    {
        if(isset($this->fileLogs[$path]) == false) $this->fileLogs[$path] = '';
        $this->fileLogs[$path] .= $data;
        $arr = explode("\n", $this->fileLogs[$path]);
        $maxKey = count($arr) - 1;
        if($maxKey > 0 && $arr[$maxKey] || ($data[strlen($data) - 1] == "\n")){
            $this->fileLogs[$path] = $arr[$maxKey];
            unset($arr[$maxKey]);
            $logData = implode("\r\n", $arr);
            $httpclient = new Httpclient();
            $httpclient->enableIpv6()->setTimeout(3000);
            $httpclient->setHeader('Content-Type', 'application/json')->request($this->cloudUrl, "POST", json_encode([
                'path' => $path,
                'body' => $logData,
            ]));
        }
    }

    /**
     * 发生nginx错误
     * @param $path
     * @param $data
     * @return void
     */
    public function nginxError($path, $data)
    {

    }

    /**
     * 文本日志
     * @param $path
     * @param $data
     * @return void
     */
    protected function text($path, $data)
    {
    }

    public function __call(string $name, array $arguments)
    {
        //var_dump("不支持的".$name);
    }
}